package com.pdwl.service.impl;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ShearCaptcha;
import cn.hutool.captcha.generator.MathGenerator;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.pdwl.common.dtos.*;
import com.pdwl.common.enums.AppHttpCodeEnum;
import com.pdwl.common.exception.CustomException;
import com.pdwl.common.utils.AppJwtUtil;
import com.pdwl.common.vo.AuthUserLoginVo;
import com.pdwl.mapper.AuthUserMapper;
import com.pdwl.pojo.AuthUser;
import com.pdwl.service.AuthUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Description: 后台登录用户业务层实现
 * @Author: TLB
 * @Date: 2023/1/11 10:45
 */
@Service
public class AuthUserServiceImpl implements AuthUserService {

    @Autowired
    private AuthUserMapper authUserMapper;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    @Override
    public PageResponseResult<List<AuthUser>> findPage(PageRequestDto<AuthUserDto> pageRequestDto) {
        pageRequestDto.checkParam();
        //处理业务
        PageHelper.<AuthUser>startPage(pageRequestDto.getPage(), pageRequestDto.getSize());
        List<AuthUser> authUsers = authUserMapper.selectPage(pageRequestDto.getEntity());
        PageInfo<AuthUser> pageInfo = new PageInfo<>(authUsers);
        return PageResponseResult.success(pageInfo);
    }

    @Override
    public ResponseResult add(AuthUser authUser) {
        if (authUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        String account = authUser.getAccount();
        String name = authUser.getName();
        String password = DigestUtils.md5DigestAsHex(authUser.getPassword().getBytes(StandardCharsets.UTF_8));
        if (StringUtils.isAnyBlank(account, name, password)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        authUserMapper.insertAuthUser(authUser);
        return ResponseResult.okResult(200,AppHttpCodeEnum.SUCCESS.getErrorMessage());

    }

    /**
     * 生成验证码
     *
     * @return
     */
    @Override
    public void captcha(String key, HttpServletResponse response) {
        if (StringUtils.isBlank(key)) {
            //throw new CustomException(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        ShearCaptcha captcha = CaptchaUtil.createShearCaptcha(200, 45, 2, 4);
        // 自定义验证码内容为四则运算方式
        captcha.setGenerator(new MathGenerator(1));
        // 重新生成code
//        captcha.createCode();
        //设置为图像模式
        response.setContentType("image/jpeg");
        //禁止图像缓存。
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        try {
            captcha.write(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
            throw new CustomException(AppHttpCodeEnum.PARAM_REQUIRE);

        }
        // key和验证码存储到redis
        try {
            stringRedisTemplate.opsForValue().set(key, captcha.getCode(), 5, TimeUnit.MINUTES);
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException(AppHttpCodeEnum.SERVER_ERROR);
        }

    }

    /**
     * 用户登录验证
     *
     * @param loginDto
     * @return
     */
    @Override
    public ResponseResult<Map<String, Object>> login(LoginDto loginDto) {
        // 校验参数
        if (loginDto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        String account = loginDto.getAccount();
        String password = DigestUtils.md5DigestAsHex(loginDto.getPassword().getBytes(StandardCharsets.UTF_8));
        String code = loginDto.getCode();
        String key = loginDto.getKey();
        if (StringUtils.isAnyBlank(account, password, code, key)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        // 校验验证码
        String redisCode = null;
        try {
            redisCode = stringRedisTemplate.opsForValue().get(key);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
        }
        // 验证码过期
        if (StringUtils.isBlank(redisCode)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_CAPTCHA_EXPIRE);
        }
        MathGenerator mathGenerator = new MathGenerator(1);
        if (!mathGenerator.verify(redisCode, code)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_CAPTCHA_ERROR);
        }
        try {
            stringRedisTemplate.delete(key);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);

        }
        //
        AuthUser authUser = authUserMapper.selectByAccount(account);
        if (authUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_AUTH_USER_NOT_FOUND);
        }
        LocalDateTime now = LocalDateTime.now();
        // 密码错误
        if (!authUser.getPassword().equals(password)) {


            authUser.setPasswordErrorLastTime(now);
            int num = authUser.getPasswordErrorNum();
            if (num == 4) {
                authUser.setStatus(false);
            }
            authUser.setPasswordErrorNum(++num);
            authUserMapper.updateById(authUser);
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        // 密码过期
        if (authUser.getPasswordExpireTime().isBefore(now)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_EXPIRE);
        }
        // 账号被禁用
        if (!authUser.getStatus()) {
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_USER_STATUS_EX);
        }

        // 登陆成功
        authUser.setLastLoginTime(now);
        authUserMapper.updateById(authUser);

        AuthUserLoginVo authUserLoginVo = new AuthUserLoginVo();
        BeanUtils.copyProperties(authUser, authUserLoginVo);
        // token
        String token = AppJwtUtil.getToken(authUser.getId());
        HashMap<String, Object> resultMap = new HashMap<>();
        resultMap.put("user", authUserLoginVo);
        resultMap.put("token", token);

        return ResponseResult.okResult(resultMap);

    }


}

